function longestConsecutive(nums = []){
let count;
let fatherMap = new Map()
init(nums)


for (let index=0; index<nums.length ; index++) {
    // 第一个元素是100， merge 100和101
    // 在map中搜索101，存在，则合并；
    merge(nums[index], nums[index] + 1)
}

console.log(fatherMap)
// Map { 100 => 100, 4 => 4, 200 => 200, 1 => 2, 3 => 4, 2 => 4 }

let max = 1
for (let index = 0; index < nums.length; index++) {
    let value = nums[index]
    // 下面语句中的find(value)很关键
    max = Math.max(max, find(value) - value + 1 )
}
console.log(max)  // max = 4

// 初始化帮派
function init(nums){
    count = nums.length
    for(let index=0; index<nums.length; index++){
        fatherMap.set(nums[index], nums[index]) //第一阶段，每个帮派的帮主是自己
    }
}

// 合并 // 两个帮主比武
function merge(i, j){
    let rootI = find(i)
    let rootJ = find(j)
    if(rootI == rootJ) return
    if(rootI == null || rootJ == null ) return
   // 结盟
    fatherMap.set(rootI, rootJ) 
    count -= 1
   
}
// 查找领队
function find(x) {
    // 判断map中是否存在指定的key
    if(!fatherMap.has(x)){
        return null
    }
    
    let root = x
    //判断key和value是否相等；
    while(fatherMap.get(root) !=  root){
        root = fatherMap.get(root)
    }

    // 路径压缩
    while(x != fatherMap.get(x)){
        let curr = x
        x = fatherMap.get(x)
        fatherMap.set(curr, root)
    }
    return root
}
}



let nums = [100,4,200,1,3,2]
longestConsecutive(nums)